from django_filters.rest_framework import DjangoFilterBackend

from rest_framework.response import Response
from rest_framework import viewsets
from rest_framework.filters import SearchFilter
from rest_framework.filters import OrderingFilter
from rest_framework import status

from XApiTestServer.models import TestCase
from XApiTestServer.pagination import MyPageNumberPagination
from XApiTestServer.serializers import CaseSerializer, CaseSumSerializer
from XApiTestServer.utils.common import *
from XApiTestServer.utils.response import *
from XApiTestServer.utils.convertor import *
from XApiTestServer.utils.auth import get_username

class CaseViewSet(viewsets.ModelViewSet):
    queryset = TestCase.objects.all()
    serializer_class = CaseSerializer
    pagination_class = MyPageNumberPagination
    filter_backends = (OrderingFilter, SearchFilter, DjangoFilterBackend)
    search_fields = ('name',)
    filterset_fields = ('belong_project', 'belong_module',)
    ordering_fields = ('update_time', )

    def nameValidator(self, project_id, casename, case_id = None):
        if case_id:
            actualname = TestCase.objects.filter(id=case_id).values('name')
            if actualname[0]['name'] == casename:
                return False
            else:
                caselist = TestCase.objects.filter(belong_project=project_id).values('name')
                for a in caselist:
                    if a['name'] == casename:
                        return True
                    else:
                        continue
                return False
        else:
            caselist = TestCase.objects.filter(belong_project=project_id).values('name')
            for a in caselist:
                if a['name'] == casename:
                    return True
                else:
                    continue
            return False

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        response_body = SUCCESS_INFO
        response_body['data'] = serializer.data
        print(response_body['data'])
        response_body['data']['pre_cases'] = db_case_pre_cases_to_vue(response_body['data']['pre_cases'])
        response_body['data']['request'] = db_case_request_to_vue(response_body['data']['request'])
        print(response_body['data']['pre_cases'])
        print(response_body['data']['request'])
        return Response(response_body)

    def create(self, request, *args, **kwargs):
        logger.info("request body: {}" .format(request.data))
        if not request.data['name']:
            msg = '用例名称(name)为必填字段'
            return Response(response_format(VERIFY_FIELDS_HINT, msg), status=status.HTTP_200_OK)
        else:
            request.data['request']['test']['name'] = request.data['name']

        if not request.data['belong_project']:
            msg = '所属项目(belong_project)为必填字段'
            return Response(response_format(VERIFY_FIELDS_HINT, msg), status=status.HTTP_200_OK)

        if not request.data['belong_module']:
            msg = '搜索模块(belong_module)为必填字段'
            return Response(response_format(VERIFY_FIELDS_HINT, msg), status=status.HTTP_200_OK)


        if not request.data['request']['test']['request']['url']:
            msg = 'request中的url为必填字段'
            return Response(response_format(VERIFY_FIELDS_HINT, msg), status=status.HTTP_200_OK)


        request.data['pre_cases'] = vue_case_pre_cases_to_db(request.data['pre_cases'])
        request.data['request'] = vue_case_request_to_db(request.data['request'])

        request.data['pre_cases'] = str(request.data['pre_cases'])
        request.data['request'] = str(request.data['request'])

        token = request.META.get("HTTP_X_TOKEN", None)
        username=get_username(token)
        request.data['author'] = username

        if self.nameValidator(request.data['belong_project'], request.data['name']):
            return Response(CASE_EXISTS, status=status.HTTP_201_CREATED)

        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            self.perform_create(serializer)
            headers = self.get_success_headers(serializer.data)
            response_body = SUCCESS_ADD
            response_body['data'] = serializer.data
            return Response(response_body, status=status.HTTP_201_CREATED, headers=headers)
        else:
            return Response(response_format(VERIFY_FIELDS_HINT, serializer.errors), status=status.HTTP_200_OK)

    def update(self, request, *args, **kwargs):
        logger.info("request body: {}" .format(request.data))
        if not request.data['name']:
            msg = '用例名称(name)为必填字段'
            return Response(response_format(VERIFY_FIELDS_HINT, msg), status=status.HTTP_200_OK)
        else:
            request.data.get('request').get('test').setdefault('name', request.data['name'])

        if not request.data['belong_project']:
            msg = '所属项目(belong_project)为必填字段'
            return Response(response_format(VERIFY_FIELDS_HINT, msg), status=status.HTTP_200_OK)

        if not request.data['belong_module']:
            msg = '搜索模块(belong_module)为必填字段'
            return Response(response_format(VERIFY_FIELDS_HINT, msg), status=status.HTTP_200_OK)


        if not request.data['request']['test']['request']['url']:
            msg = 'request中的url为必填字段'
            return Response(response_format(VERIFY_FIELDS_HINT, msg), status=status.HTTP_200_OK)


        request.data['pre_cases'] = vue_case_pre_cases_to_db(request.data['pre_cases'])
        request.data['request'] = vue_case_request_to_db(request.data['request'])

        request.data['pre_cases'] = str(request.data['pre_cases'])
        request.data['request'] = str(request.data['request'])

        token = request.META.get("HTTP_X_TOKEN", None)
        username=get_username(token)
        request.data['author'] = username

        if self.nameValidator(request.data['belong_project'], request.data['name'],request.data['id']):
            return Response(CASE_EXISTS, status=status.HTTP_201_CREATED)

        serializer = self.get_serializer(data=request.data)

        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        if serializer.is_valid(raise_exception=True):
            self.perform_update(serializer)

            response_body = SUCCESS_UPDATE
            response_body['data'] = serializer.data
            return Response(response_body)
        else:
            return Response(response_format(VERIFY_FIELDS_HINT, serializer.errors), status=status.HTTP_200_OK)

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        self.perform_destroy(instance)
        response_body = SUCCESS_DEL
        return Response(response_body)


class CaseSumViewSet(viewsets.ModelViewSet):
    queryset = TestCase.objects.all()
    serializer_class = CaseSumSerializer
    filter_backends = (OrderingFilter, SearchFilter, DjangoFilterBackend)
    filterset_fields = ('name',)
    ordering_fields = ('update_time',)

    def list(self, request, *args, **kwargs):
        queryset = TestCase.objects.all()

        serializer = self.get_serializer(queryset, many=True)

        response_body = SUCCESS_LIST
        response_body['results'] = serializer.data

        return Response(response_body)
